import { initializeScrollPosition, initializeZRender } from './core/initialization';
import { ScheduleRenderer } from './core/schedule-renderer';
import { useCalendarStore } from '../stores/calendar';
import { useScheduleStore } from '../stores/schedule';

class ScheduleApp {
  // ZRender实例
  private zr: any;
  // 滚动位置
  private scrollState: ScrollState;
  // 排班表渲染器
  private scheduleRenderer: ScheduleRenderer | null;
  // 日历store
  private calendarStore: any;
  // 排班store
  private scheduleStore: any;

  constructor() {
    this.scrollState = {
      lastScrollX: 0,
      lastScrollY: 0,
    };
    this.scheduleRenderer = null;
    this.calendarStore = null;
    this.scheduleStore = null;
  }

  init() {
    // 初始化ZRender
    this.zr = initializeZRender();

    // 初始化滚动位置
    this.scrollState = initializeScrollPosition();

    // 初始化stores
    this.calendarStore = useCalendarStore();
    this.scheduleStore = useScheduleStore();

    // 初始化排班数据
    this.scheduleStore.initializeSchedules();

    // 从store获取日期范围
    const dateRange = this.calendarStore.dateRange;

    // 从store获取排班数据
    const schedules = this.scheduleStore.schedules;

    // 创建排班表渲染器
    this.scheduleRenderer = new ScheduleRenderer(this.zr, schedules, this.scrollState, dateRange);

    // 初始化store监听
    this.scheduleRenderer.initStoreWatcher();

    // 绘制排班表
    this.scheduleRenderer.draw(true);
  }

  // 设置日期范围
  setDateRange(start: string, end: string) {
    if (!this.calendarStore) {
      this.calendarStore = useCalendarStore();
    }
    this.calendarStore.setDateRange({ start, end });
    // 如果渲染器已存在，更新其日期范围并重新绘制
    if (this.scheduleRenderer) {
      this.scheduleRenderer.updateDateRange({ start, end });
      this.scheduleRenderer.draw(true);
    }
  }

  // 添加排班相关的方法
  addSchedule(personId: string, shift: Shift) {
    if (this.scheduleStore) {
      this.scheduleStore.addSchedule(personId, shift);
    }
  }

  updateShift(personId: string, shiftId: string, updatedShift: Partial<Shift>) {
    if (this.scheduleStore) {
      this.scheduleStore.updateShift(personId, shiftId, updatedShift);
    }
  }

  removeShift(personId: string, shiftId: string) {
    if (this.scheduleStore) {
      this.scheduleStore.removeShift(personId, shiftId);
    }
  }

  // 清理资源
  destroy() {
    if (this.scheduleRenderer) {
      this.scheduleRenderer.destroy();
    }
  }
}

export { ScheduleApp };
